from flask import Flask, render_template, request
from ansys_parser import AnsysParser
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
import os
import shutil

# 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

oss_url = os.getenv("OSS_URL")
oss_bucket = os.getenv("OSS_BUCKET")

bucket = oss2.Bucket(auth, oss_url, oss_bucket)


app = Flask(__name__, template_folder="../frontend/dist", static_folder="../frontend/dist/assets")

global parser

@app.route("/")
def index():
    return render_template("index.html")


@app.route("/import", methods=["POST"])
def model_import():
    data = request.get_json()
    model_path = data.get("modelPath")
    result_path = data.get("resultPath")
    try:
        global parser
        parser = AnsysParser(model_path, result_path)
        folder = "/home/paraview/data"
        if not os.path.exists(folder):
            os.makedirs(folder, exist_ok=True)
        for i in range(1000):
            target_path = f'/home/paraview/data/{i}_file.vtu'
            if not os.path.isfile(target_path):
                shutil.copy2('/home/file.vtu', target_path)
                break
    except Exception as e:
        print(e)
        return {
            "success": False,
            "message": str(e)
        }
    else:
        return {
            "success": True,
            "message": "导入成功",
            "data": parser.model_info
        }


@app.route("/query", methods=["GET"])
def query():
    try:
        global parser
        parser.result_info
    except Exception as e:
        return {
            "success": False,
            "message": str(e)
        }
    else:
        return {
            "success": True,
            "message": "数据查询成功",
            "columns": parser.result_info[0],
            "data": parser.result_info[1]
        }


@app.route("/oss_file", methods=["GET"])
def get_oss_file():
    directory = request.args.get('directory', '')
    print(directory)
    res = []
    for obj in oss2.ObjectIteratorV2(
        bucket, prefix=directory, delimiter='/', start_after=directory, fetch_owner=True
    ):
        if obj.is_prefix():  # 判断obj为文件夹。
            name = obj.key.split('/')[-2]
            directory = True
        else:
            name = obj.key.split('/')[-1]
            directory = False
        res.append({'key': obj.key, 'name': name, 'directory': directory})
    return {
        "success": True,
        "data": res,
    }


if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=9000)
